package com.halflife.netty.bigfiletransf;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;

public class BigFileServer {
    private NioEventLoopGroup serverEvents;
    private NioEventLoopGroup clientEvents;
    private ServerBootstrap serverBootstrap;
    private ChannelFuture channelFuture;

    public BigFileServer() throws InterruptedException {
        try {
            this.serverEvents = new NioEventLoopGroup(1);
            this.clientEvents = new NioEventLoopGroup(3);
            this.serverBootstrap = new ServerBootstrap();
            this.configServerBootStrap();
            this.channelFuture.sync();
            this.channelFuture.channel().closeFuture().sync();
        } finally {
            this.serverEvents.shutdownGracefully();
            this.clientEvents.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        try {
            BigFileServer bigFileServer = new BigFileServer();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void configServerBootStrap() {
        this.serverBootstrap.group(serverEvents, clientEvents);
        this.serverBootstrap.channel(NioServerSocketChannel.class);
        this.serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
//                ch.pipeline().addLast()
                ch.pipeline().addLast(new ObjectEncoder());
                ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingConcurrentResolver(null))) ;
                // 自定义处理器
                ch.pipeline().addLast( new FileHandler());
            }
        });
        this.channelFuture = this.serverBootstrap.bind(new InetSocketAddress("127.0.0.1",9090));
    }
}
